<?php
/**
 * 春哥团队（www.cgtblog.com） - 春哥多端多商户万能DIY商城系统
 * Copyright © 2024 春哥技术团队 保留所有权利
 * =========================================================

 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\controller;
use think\facade\Db;
class ApiYuyue extends ApiCommon{
	public function getprolist(){
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['ischecked','=',1];
		//$where[] = ['status','=',1];
		$nowtime = time();
		$where[] = Db::raw("`status`=1  or (`status`=2 and unix_timestamp(start_time)<=$nowtime and unix_timestamp(end_time)>=$nowtime)");

		if(input('param.bid')){
			$bid = input('param.bid/d');
		}else{
			$bid = 0;
		}
		if($bid){
			$where[] = ['bid','=',$bid];
		}else{
			$business_sysset = Db::name('business_sysset')->where('aid',aid)->find();
			if(!$business_sysset || $business_sysset['status']==0 || $business_sysset['product_isshow']==0){
				$where[] = ['bid','=',0];
			}
		}
		
		if(input('param.field') && input('param.order')){
			$order = input('param.field').' '.input('param.order').',sort,id desc';
		}else{
			$order = 'sort desc,id desc';
		}
		//分类 
		if(input('param.cid')){
			$cid = input('post.cid') ? input('post.cid/d') : input('param.cid/d');
			//子分类
			$clist = Db::name('yuyue_category')->where('aid',aid)->where('pid',$cid)->column('id');
			if($clist){
				$clist2 = Db::name('yuyue_category')->where('aid',aid)->where('pid','in',$clist)->column('id');
				$cCate = array_merge($clist, $clist2, [$cid]);
				if($cCate){
					$whereCid = [];
					foreach($cCate as $k => $c2){
						$whereCid[] = "find_in_set({$c2},cid)";
					}
                    $where[] = Db::raw(implode(' or ',$whereCid));
				}
			} else {
                $where[] = Db::raw("find_in_set(".$cid.",cid)");
            }
		}
        //优惠券可用商品列表
        $cpid = input('param.cpid/d');
        if($cpid > 0){
            $coupon = Db::name('coupon')->where('id',$cpid)->find();
            $where[] = ['bid','=',$coupon['bid']];
            if($coupon['fwtype']==4){ //指定商品
                $where[] = ['id','in',$coupon['yuyue_productids']];
            }
        }

		if(input('param.keyword')){
			$where[] = ['name','like','%'.input('param.keyword').'%'];
		}
		$pernum = 10;
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		$field = "id,pic,name,sales,sell_price,danwei";
        $datalist = Db::name('yuyue_product')->field($field)->where($where)->page($pagenum,$pernum)->order($order)->select()->toArray();
		if(!$datalist) $datalist = [];
		return $this->json(['status'=>1,'data'=>$datalist]);
	}
	public function prolist(){
		if(input('param.bid')){
			$bid = input('param.bid/d');
		}else{
			$bid = 0;
		}
		//分类
		if(input('param.cid')){
			$clist = Db::name('yuyue_category')->where('aid',aid)->where('pid',input('param.cid/d'))->where('status',1)->order('sort desc,id')->select()->toArray();
			if(!$clist) $clist = [];
		}else{
			$clist = Db::name('yuyue_category')->where('aid',aid)->where('bid',$bid)->where('pid',0)->where('status',1)->order('sort desc,id')->select()->toArray();
			if(!$clist) $clist = [];
		}
		return $this->json(['clist'=>$clist]);
	}
	
	//分类商品
	public function classify(){
		if(input('param.bid')){
			$bid = input('param.bid/d');
		}else{
			$bid = 0;
		}
		$clist = Db::name('yuyue_category')->where('aid',aid)->where('pid',0)->where('bid',$bid)->where('status',1)->order('sort desc,id')->select()->toArray();
		foreach($clist as $k=>$v){
			$rs = Db::name('yuyue_category')->where('aid',aid)->where('pid',$v['id'])->where('status',1)->order('sort desc,id')->select()->toArray();
			if(!$rs) $rs = [];
			$clist[$k]['child'] = $rs;
		}
		return $this->json(['status'=>1,'data'=>$clist]);
	}
	//商品
	public function product(){
		$proid = input('param.id/d');
		$product = Db::name('yuyue_product')->where('id',$proid)->where('aid',aid)->find();
		if(!$product) return $this->json(['status'=>0,'msg'=>'商品不存在']);
		if($product['status']==0) return $this->json(['status'=>0,'msg'=>'商品未上架']);
		if($product['ischecked']!=1) return $this->json(['status'=>0,'msg'=>'商品未审核']);
		
		if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time())){
			return $this->json(['status'=>0,'msg'=>'商品未上架']);
		}
		if($product['status']==2) $product['status']=1;
		if(!$product['pics']) $product['pics'] = $product['pic'];
		$product['pics'] = explode(',',$product['pics']);
		$product = $this->formatproduct($product);

		//优惠券
		$couponlist = Db::name('coupon')->where('aid',aid)->where('bid',$product['bid'])->where('tolist',1)->where('type','in','1,4')->where("unix_timestamp(starttime)<=".time()." and unix_timestamp(endtime)>=".time())->order('sort desc')->select()->toArray();
		$newcplist = [];
		foreach($couponlist as $k=>$v){
			$gettj = explode(',',$v['gettj']);
			if(!in_array('-1',$gettj) && !in_array($this->member['levelid'],$gettj)){ //不是所有人
				continue;
			}
            if($v['isgive'] == 2) continue;//仅转赠
            //0全场通用,4指定服务商品
            if(!in_array($v['fwtype'],[0,4])){
                continue;
            }
            if($v['fwtype']==4){//指定服务商品可用
                $productids = explode(',',$v['yuyue_productids']);
                if(!in_array($product['id'],$productids)){
                    continue;
                }
            }
			$haveget = Db::name('coupon_record')->where('aid',aid)->where('mid',mid)->where('couponid',$v['id'])->count();
			$v['haveget'] = $haveget;
			//$v['starttime'] = date('m-d H:i',strtotime($v['starttime']));
			//$v['endtime'] = date('m-d H:i',strtotime($v['endtime']));
            if($v['yxqtype'] == 1){
                $yxqtime = explode(' ~ ',$v['yxqtime']);
                $v['yxqdate'] = strtotime($yxqtime[1]);
            }elseif($v['yxqtype'] == 2){
                $v['yxqdate'] = time() + 86400 * $v['yxqdate'];
            }elseif($v['yxqtype'] == 3) {
                //次日起计算有效期
                $v['yxqdate'] = strtotime(date('Y-m-d')) + 86400 * ($v['yxqdate'] + 1) - 1;
            }
            if($v['bid'] > 0){
                $v['bname'] = Db::name('business')->where('aid',aid)->where('id',$v['bid'])->value('name');
            }
			$newcplist[] = $v;
		}
		//是否收藏
		$rs = Db::name('member_favorite')->where('aid',aid)->where('mid',mid)->where('proid',$proid)->where('type','yuyue')->find();
		if($rs){
			$isfavorite = true;
		}else{
			$isfavorite = false;
		}
		//获取评论
		$commentlist = Db::name('yuyue_comment')->where('aid',aid)->where('proid',$proid)->where('status',1)->order('id desc')->limit(10)->select()->toArray();
		if(!$commentlist) $commentlist = [];
		foreach($commentlist as $k=>$pl){
			$commentlist[$k]['createtime'] = date('Y-m-d H:i',$pl['createtime']);
			if($commentlist[$k]['content_pic']) $commentlist[$k]['content_pic'] = explode(',',$commentlist[$k]['content_pic']);
		}
		$commentcount = Db::name('yuyue_comment')->where('aid',aid)->where('proid',$proid)->where('status',1)->count();

		//添加浏览历史
		if(mid){
			$rs = Db::name('member_history')->where('aid',aid)->where('mid',mid)->where('proid',$proid)->where('type','yuyue')->find();
			if($rs){
				Db::name('member_history')->where('id',$rs['id'])->update(['createtime'=>time()]);
			}else{
				Db::name('member_history')->insert(['aid'=>aid,'mid'=>mid,'proid'=>$proid,'type'=>'yuyue','createtime'=>time()]);
			}
		}
        //商品服务
        if($product['fuwupoint']){
            $fuwulist = explode(' ', $product['fuwupoint']);
        }else{
            $fuwulist = [];
        }
		if($product['fwid']){
			$fuwulist2 = Db::name('yuyue_fuwu')->where('aid',aid)->where('status',1)->where('id','in',$product['fwid'])->order('sort desc,id')->select()->toArray();
		}else{
			$fuwulist2 = [];
		}

		$sysset = Db::name('admin_set')->where('aid',aid)->field('name,logo,desc,fxjiesuantype,tel,kfurl,gzts,ddbb')->find();

		if($product['balance'] > 0){
			$product['advance_price'] = round($product['sell_price'] * (1 - $product['balance'] *0.01),2);
			$product['balance_price'] = round($product['sell_price'] * $product['balance'] *0.01,2);
		}
		if($product['bid']!=0){
			$business = Db::name('business')->where('aid',aid)->where('id',$product['bid'])->field('id,name,logo,desc,tel,address,sales,kfurl')->find();
		}else{
			$business = $sysset;
		}
		$product['detail'] = \app\common\System::initpagecontent($product['detail'],aid,mid,platform);
		$product['comment_starnum'] = floor($product['comment_score']);
		
		$sysset['showgzts'] = false;
		//关注提示
		if(platform == 'mp'){
			$sysset['gzts'] = explode(',',$sysset['gzts']);
			if(in_array('2',$sysset['gzts']) && $this->member['subscribe']==0){
				$appinfo = \app\common\System::appinfo(aid,'mp');
				$sysset['qrcode'] = $appinfo['qrcode'];
				$sysset['gzhname'] = $appinfo['nickname'];
				$sysset['showgzts'] = true;
			}
		}
		//获取设置
		$set = Db::name('yuyue_set')->field('ad_status,ad_pic,ad_link,video_status,video_tag,video_title')->where('aid',aid)->where('bid',0)->find();
        if($set['video_tag']) $set['video_tag'] = explode(',',$set['video_tag']);
        else $set['video_tag'] = [];
		$times = [];
		$j = $product['wanhour'] - $product['zaohour'];

		for($i=strtotime($product['zaohour'].':00') ;$i<=strtotime($product['wanhour'].':00') ; $i=$i+60*$product['timejg']){
			$times[]=date("H:i",$i);
		}
		if($product['rqtype']==1){
			$datelist = $this->GetWeeks($product['yyzhouqi']);
		}elseif($product['rqtype']==2){
			$datelist = [];
			$yybeigntime = strtotime($product['yybegintime']);
			$yyendtime = strtotime($product['yyendtime']);
			$days= ($yyendtime-$yybeigntime)/86400;
			for ($i=0;$i<=$days;$i++){
				$year=date('Y',$yybeigntime+86400*$i).'年';
				$month=date('m',$yybeigntime+86400*$i).'月';
				$day=date('d',$yybeigntime+86400*$i);
				$week=date('w',$yybeigntime+86400*$i);
				if ($week=='1'){
					$week='周一';
					$key=1;
				}elseif ($week=='2'){
					$week='周二';
					$key=2;
				}elseif ($week=='3'){
					$week='周三';
					$key=3;
				}elseif ($week=='4'){
					$week='周四';
					$key=4;
				}elseif ($week=='5'){
					$week='周五';
					$key =5;
				}elseif ($week=='6'){
					$week='周六';
					$key=6;
				}elseif ($week=='0'){
					$week='周日';
					$key=0;
				}
				$datelist[$i]['key'] = $key;
				$datelist[$i]['weeks'] = $week;
				$datelist[$i]['date'] = $month.$day;
				$datelist[$i]['year'] = $year;

			}
		}elseif($product['rqtype']==3){
	
			$timeday = explode(',',$product['yytimeday']);
			foreach($timeday as $k=>$d){
				$year=date('Y',time()+86400).'年';
				$month=date('m',time()+86400).'月';
				$day=date('d',time()+86400*($d-1));
				if($d==1) $week='今天';
				if($d==2) $week='明天';
				if($d==3) $week='后天';
				if($d==4) $week='大后天';
				if($d>4) $week='';
				$datelist[$k]['key'] = $k;
				$datelist[$k]['weeks'] = $week;
				$datelist[$k]['date'] = $month.$day;
				$datelist[$k]['year'] = $year;
			}
		}
		$minprice = 999999999999999;
		$maxprice = 0;
		$gglist = Db::name('yuyue_guige')->where('proid',$product['id'])->select()->toArray();
		foreach($gglist as $k=>$v){
			if($v['sell_price'] < $minprice){
				$minprice = $v['sell_price'];
			}
			if($v['sell_price'] > $maxprice){
				$maxprice = $v['sell_price'];
			}
		}
		$product['min_price'] = round($minprice,2);
		$product['max_price'] = round($maxprice,2);

		$isfuwu = false;
		$shopset_field = 'showjd,comment,showcommission,hide_sales,hide_stock,show_lvupsavemoney';
        $shopset = Db::name('shop_sysset')->where('aid',aid)->field($shopset_field)->find();
		$rdata = [];
		$rdata['status'] = 1;
		$rdata['title'] = $product['name'];
		$rdata['isfuwu'] = $isfuwu;
        $rdata['set'] = $set ? $set : [];
		$rdata['isfavorite'] = $isfavorite;
		$rdata['product'] = $product;
        $rdata['fuwulist2'] = $fuwulist2;
        $rdata['fuwulist'] = $fuwulist;
		$rdata['business'] = $business;
		$rdata['shopset'] = $shopset;
		$rdata['commentlist'] = $commentlist;
		$rdata['commentcount'] = $commentcount;
		$rdata['datelist'] = $datelist;
		$rdata['daydate'] = $daydate;
		$rdata['sysset'] = $sysset;
		//$rdata['couponlist'] = $newcplist;
		return $this->json($rdata);
	}
	//获取商品详情
	public function getproductdetail(){
		$proid = input('param.id/d');
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['id','=',$proid];
		$field = "bid,id,pic,name,sales,sell_price,guigedata,status,ischecked,start_time,end_time,minbuynum";
		$product = Db::name('yuyue_product')->field($field)->where($where)->find();
		if(!$product){
			return $this->json(['status'=>0,'msg'=>'商品不存在']);
		}
		$product = $this->formatproduct($product);
		if($product['status']==0) return $this->json(['status'=>0,'msg'=>'商品已下架']);
		if($product['ischecked']!=1) return $this->json(['status'=>0,'msg'=>'商品未审核']);
		if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time())){
			return $this->json(['status'=>0,'msg'=>'商品未上架']);
		}

		$gglist = Db::name('yuyue_guige')->where('proid',$product['id'])->select()->toArray();
		$guigelist = array();
		foreach($gglist as $k=>$v){
			if($product['balance'] > 0){
				$v['advance_price'] = round($v['sell_price'] * (1 - $product['balance']*0.01),2);
				$v['balance_price'] = round($v['sell_price'] * $product['balance']*0.01,2);
			}else{
				$v['balance_price'] = 0;
			}
			$guigelist[$v['ks']] = $v;
		}
		$guigedata = json_decode($product['guigedata'],true);
		$ggselected = [];
		foreach($guigedata as $v) {
			$ggselected[] = 0;
		}
		$ks = implode(',',$ggselected);
		$set = Db::name('yuyue_set')->where('aid',aid)->field('yuyue_numtext')->find();
		return $this->json(['status'=>1,'product'=>$product,'guigelist'=>$guigelist,'guigedata'=>$guigedata,'ggselected'=>$ggselected,'ks'=>$ks,'set'=>$set]);
	}
	//商品评价
	public function commentlist(){
		$proid = input('param.proid/d');
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		$pernum = 20;
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['proid','=',$proid];
		$where[] = ['status','=',1];
		$datalist = Db::name('yuyue_comment')->where($where)->page($pagenum,$pernum)->order('id desc')->select()->toArray();
		if(!$datalist) $datalist = [];
		foreach($datalist as $k=>$pl){
			$datalist[$k]['createtime'] = date('Y-m-d H:i',$pl['createtime']);
			if($datalist[$k]['content_pic']) $datalist[$k]['content_pic'] = explode(',',$datalist[$k]['content_pic']);
		}
		if(request()->isPost()){
			return $this->json(['status'=>1,'data'=>$datalist]);
		}
		$rdata = [];
		$rdata['datalist'] = $datalist;
		return $this->json($rdata);
	}
	//商品海报
	function getposter(){
		$this->checklogin();
		$post = input('post.');
		$platform = platform;
		$page = '/activity/yuyue/product';
		$scene = 'id_'.$post['proid'].'-pid_'.$this->member['id'];
		//if($platform == 'mp' || $platform == 'h5' || $platform == 'app'){
		//	$page = PRE_URL .'/h5/'.aid.'.html#'. $page;
		//}
		$posterset = Db::name('admin_set_poster')->where('aid',aid)->where('type','yuyue')->where('platform',$platform)->order('id')->find();

		$posterdata = Db::name('member_poster')->where('aid',aid)->where('mid',mid)->where('scene',$scene)->where('type','yuyue')->where('posterid',$posterset['id'])->find();
		if(true || !$posterdata){
			$product = Db::name('yuyue_product')->where('id',$post['proid'])->find();
			$product = $this->formatproduct($product);
			$sysset = Db::name('admin_set')->where('aid',aid)->find();
			$textReplaceArr = [
				'[头像]'=>$this->member['headimg'],
				'[昵称]'=>$this->member['nickname'],
				'[姓名]'=>$this->member['realname'],
				'[手机号]'=>$this->member['mobile'],
				'[商城名称]'=>$sysset['name'],
				'[商品名称]'=>$product['name'],
				'[商品销售价]'=>$product['sell_price'],
				'[商品市场价]'=>$product['sell_price'],
				'[商品图片]'=>$product['pic'],
			];

			$poster = $this->_getposter(aid,$platform,$posterset['content'],$page,$scene,$textReplaceArr);
			$posterdata = [];
			$posterdata['aid'] = aid;
			$posterdata['mid'] = $this->member['id'];
			$posterdata['scene'] = $scene;
			$posterdata['page'] = $page;
			$posterdata['type'] = 'yuyue';
			$posterdata['poster'] = $poster;
			$posterdata['createtime'] = time();
			Db::name('member_poster')->insert($posterdata);
		}
		return $this->json(['status'=>1,'poster'=>$posterdata['poster']]);
	}


	//订单提交页
	public function buy(){
		$this->checklogin();
		$prodata = explode('-',input('param.prodata'));
		$multi_promotion = 0;
        $adminset = Db::name('admin_set')->where('aid',aid)->find();
		//会员折扣
		$userlevel = Db::name('member_level')->where('aid',aid)->where('id',$this->member['levelid'])->find();
		$userinfo = [];
		$userinfo['id'] = $this->member['id'];
		$userinfo['realname'] = $this->member['realname'];
		$userinfo['tel'] = $this->member['tel'];
		$userinfo['discount'] = $userlevel['discount'];

		$allbuydata = [];
		$autofahuo  = 0;

		foreach($prodata as $key=>$gwc){
			list($proid,$ggid,$num) = explode(',',$gwc);
			$product = Db::name('yuyue_product')->where('aid',aid)->where('ischecked',1)->where('id',$proid)->find();
			if($product['status']==0){
				return $this->json(['status'=>0,'msg'=>'商品未上架']);
			}
			if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time())){
				return $this->json(['status'=>0,'msg'=>'商品未上架']);
			}

			if($product['freighttype'] == 3 || $product['freighttype'] == 4) $autofahuo = $product['freighttype'];
			$guige = Db::name('yuyue_guige')->where('id',$ggid)->find();
			if(!$allbuydata[$product['bid']]) $allbuydata[$product['bid']] = [];
			if(!$allbuydata[$product['bid']]['prodata']) $allbuydata[$product['bid']]['prodata'] = [];
			$allbuydata[$product['bid']]['prodata'][] = ['product'=>$product,'guige'=>$guige,'num'=>$num];
		}
		
		if($product['rqtype']==1){
			$datelist = $this->GetWeeks($product['yyzhouqi']);
		}elseif($product['rqtype']==2){
			$datelist = [];
			$yybeigntime = strtotime($product['yybegintime']);
			$yyendtime = strtotime($product['yyendtime']);
			$days= ($yyendtime-$yybeigntime)/86400;
			for ($i=0;$i<=$days;$i++){
				$year=date('Y',$yybeigntime+86400*$i).'年';
				$month=date('m',$yybeigntime+86400*$i).'月';
				$day=date('d',$yybeigntime+86400*$i);
				$week=date('w',$yybeigntime+86400*$i);
				if ($week=='1'){
					$week='周一';
					$key=1;
				}elseif ($week=='2'){
					$week='周二';
					$key=2;
				}elseif ($week=='3'){
					$week='周三';
					$key=3;
				}elseif ($week=='4'){
					$week='周四';
					$key=4;
				}elseif ($week=='5'){
					$week='周五';
					$key =5;
				}elseif ($week=='6'){
					$week='周六';
					$key=6;
				}elseif ($week=='0'){
					$week='周日';
					$key=0;
				}
				$datelist[$i]['key'] = $key;
				$datelist[$i]['weeks'] = $week;
				$datelist[$i]['date'] = $month.$day;
				$datelist[$i]['year'] = $year;

			}
		}elseif($product['rqtype']==3){
	
			$timeday = explode(',',$product['yytimeday']);
			foreach($timeday as $k=>$d){
				$year=date('Y',time()+86400).'年';
				$month=date('m',time()+86400).'月';
				$day=date('d',time()+86400*($d-1));
				if($d==1) $week='今天';
				if($d==2) $week='明天';
				if($d==3) $week='后天';
				if($d==4) $week='大后天';
				if($d>4) $week='';
				$datelist[$k]['key'] = $k;
				$datelist[$k]['weeks'] = $week;
				$datelist[$k]['date'] = $month.$day;
				$datelist[$k]['year'] = $year;
			}
		}



		//服务人员
		$worker_id = input('param.worker_id');
		if($worker_id){
			$fw = Db::name('yuyue_worker')->where('aid',aid)->where('id',$worker_id)->find();
			if(!$fw) $fw = [];
		}

		$address = Db::name('member_address')->where('aid',aid)->where('mid',mid)->order('isdefault desc,id desc')->find();
		if(!$address) $address = [];
		$needLocation = 0;
		$allproduct_price = 0;
		foreach($allbuydata as $bid=>$buydata){
			if($bid!=0){
				$business = Db::name('business')->where('id',$bid)->field('id,aid,cid,name,logo,tel,address,sales,longitude,latitude,start_hours,end_hours,start_hours2,end_hours2,start_hours3,end_hours3,end_buy_status,invoice,invoice_type,province,city,district')->find();
				
				$is_open = 0;
				if($is_open==0){
					if($business['start_hours'] != $business['end_hours']){
						$start_time = strtotime(date('Y-m-d '.$business['start_hours']));
						$end_time = strtotime(date('Y-m-d '.$business['end_hours']));
						if(($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time > $end_time && ($start_time > time() && $end_time < time()))){
							//return $this->json(['status'=>-4,'msg'=>'商家不在营业时间']);
						}else{
							$is_open = 1;
						}
					}else{
						$is_open = 1;
					}
				}
				if($is_open==0){
					$start_time = strtotime(date('Y-m-d '.$business['start_hours2']));
					$end_time = strtotime(date('Y-m-d '.$business['end_hours2']));
					if($start_time == $end_time || ($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time > $end_time && ($start_time > time() && $end_time < time()))){
						//return $this->json(['status'=>-4,'msg'=>'商家不在营业时间']);
					}else{
						$is_open = 1;
					}
				}
				if($is_open==0){
					$start_time = strtotime(date('Y-m-d '.$business['start_hours3']));
					$end_time = strtotime(date('Y-m-d '.$business['end_hours3']));
					if($start_time == $end_time || ($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time > $end_time && ($start_time > time() && $end_time < time()))){
						//return $this->json(['status'=>-4,'msg'=>'商家不在营业时间']);
					}else{
						$is_open = 1;
					}
				}
				if($is_open == 0 && $business['end_buy_status'] == 0){
                    $open_time = $business['start_hours'].'-'.$business['end_hours'];
                    if($business['start_hours2'] != $business['end_hours2']){
                        $open_time .= ' '.$business['start_hours2'].'-'.$business['end_hours2'];
                    }
                    if($business['start_hours3'] != $business['end_hours3']){
                        $open_time .= ' '.$business['start_hours3'].'-'.$business['end_hours3'];
                    }
                    return $this->json(['status'=>-4,'msg'=>'商家已打烊，营业时间为:'.$open_time]);
				}
			}else{
				$business = Db::name('admin_set')->where('aid',aid)->field('id,name,logo,desc,tel,province,city,district,address')->find();
                $business['province'] = $business['province']?$business['province']:'';
                $business['city'] = $business['city']?$business['city']:'';
                $business['district'] = $business['district']?$business['district']:'';
			}
		
			$product_priceArr = [];
			$product_price = 0;
			$needzkproduct_price = 0;
			$totalweight = 0;
			$totalnum = 0;
			$prodataArr = [];
			$proids = [];
			$cids = [];
			foreach($buydata['prodata'] as $prodata){
				$product_priceArr[] = $prodata['guige']['sell_price'] * $prodata['num'];
				$product_price += $prodata['guige']['sell_price'] * $prodata['num'];
				if($prodata['product']['balance']){
					$product_price = $product_price * (1-$prodata['product']['balance']*0.01);
				}
				if($prodata['product']['lvprice']==0 && $prodata['product']['no_discount'] == 0){ //未开启会员价
					$needzkproduct_price += $prodata['guige']['sell_price'] * $prodata['num'];
				}
				$totalprice = $prodata['guige']['sell_price'] * $prodata['num'];
				$totalnum += $prodata['num'];
				$prodataArr[] = $prodata['product']['id'].','.$prodata['guige']['id'].','.$prodata['num'];
				$proids[] = $prodata['product']['id'];
				$cids = array_merge(explode(',',$prodata['product']['cid']),$cids);
			}
			$prodatastr = implode('-',$prodataArr);
			
			$yyset = db('yuyue_set')->where('aid',aid)->find();
			if(!$yyset) $yyset=[];
			$leveldk_money = 0;
			if($yyset['discount']==1 && $userlevel && $userlevel['discount']>0 && $userlevel['discount']<10){
				$leveldk_money = $needzkproduct_price * (1 - $userlevel['discount'] * 0.1);
			}
			$leveldk_money = round($leveldk_money,2);
			$price = $product_price - $leveldk_money;
            $manjian_money = 0;
			$newcouponlist = [];
			if($yyset['iscoupon']==1){
                $bwhere2 = [];
                $bwhere2 = [['type','in','1,4,10']];
				if($bid > 0){
					$business = Db::name('business')->where('aid',aid)->where('id', $bid)->find();
					$bcids = $business['cid'] ? explode(',',$business['cid']) : [];
				}else{
					$bcids = [];
				}
				if($bcids){
					$whereCid = [];
					foreach($bcids as $bcid){
						$whereCid[] = "find_in_set({$bcid},canused_bcids)";
					}
					$whereCids = implode(' or ',$whereCid);
				}else{
					$whereCids = '0=1';
				}

				$couponList = Db::name('coupon_record')->where('aid',aid)->where('mid',mid)->where($bwhere2)->where('status',0)
					->whereRaw("bid=-1 or bid=".$bid." or (bid=0 and (canused_bids='all' or find_in_set(".$bid.",canused_bids) or ($whereCids)))")->where('minprice','<=',$price - $manjian_money)->where('starttime','<=',time())->where('endtime','>',time())
				->order('id desc')->select()->toArray();
                if(!$couponList) $couponList = [];
				foreach($couponList as $k=>$v){
					//$couponList[$k]['starttime'] = date('m-d H:i',$v['starttime']);
					//$couponList[$k]['endtime'] = date('m-d H:i',$v['endtime']);
					$couponinfo = Db::name('coupon')->where('aid',aid)->where('id',$v['couponid'])->find();
                    if(empty($couponinfo)){
                        continue;
                    }
                    //不可自用
                    if($couponinfo['isgive']==2){
                        continue;
                    }
                    //适用场景
                    if($couponinfo['fwscene'] !==0){
                        continue;
                    }
                    //0全场通用,4指定服务商品
                    if(in_array($couponinfo['fwtype'],[0,4])){
                        if($couponinfo['fwtype']==4){//指定服务商品可用
                            $productids = explode(',',$couponinfo['yuyue_productids']);
                            if(!array_intersect($proids,$productids)){
                                continue;
                            }
                        }
                        if($v['bid'] > 0){
                            $binfo = Db::name('business')->where('aid',aid)->where('id',$v['bid'])->find();
                            $v['bname'] = $binfo['name'];
                        }
                        $newcouponlist[] = $v;
                    }else{
                        continue;
                    }
				}
			}

			//查看服务方式
			if($product['fwtype']){
					$fwtype = explode(',',$product['fwtype']);
					$fwtypelist = [];
				    if(in_array(2,$fwtype)) $fwtypelist[] =  ['name'=>'上门服务','key'=>2];
					if(in_array(1,$fwtype))	$fwtypelist[] = ['name'=>'到店服务','key'=>1];
			}
			//取出设置的自定义表单
			//$yyset = db('yuyue_set')->where('aid',aid)->find();
			$couponList = $newcouponlist;
		
			$allbuydata[$bid]['bid'] = $bid;
			$allbuydata[$bid]['business'] = $business;
			$allbuydata[$bid]['prodatastr'] = $prodatastr;
			$allbuydata[$bid]['couponList'] = $couponList;
			$allbuydata[$bid]['couponCount'] = count($couponList);
			$allbuydata[$bid]['sell_price'] = round($price,2);
			$allbuydata[$bid]['leveldk_money'] = $leveldk_money;
			$allbuydata[$bid]['coupon_money'] = 0;
			$allbuydata[$bid]['coupontype'] = 1;
			$allbuydata[$bid]['couponrid'] = 0;
			$allbuydata[$bid]['editorFormdata'] = [];
			$allbuydata[$bid]['product_price'] = round($product_price,2);
			$allbuydata[$bid]['balance'] = $product['balance'];
			$allbuydata[$bid]['formdata'] = json_decode($product['formdata'],true);
			$allbuydata[$bid]['fwtype'] = $product['fwtype'];
			$allbuydata[$bid]['fwpeople'] = $product['fwpeople'];
			$allbuydata[$bid]['fw'] = $fw;
			$allbuydata[$bid]['bid'] = $bid;
			$allproduct_price += $product_price;
		}
		
		$isdate = false;
		$rdata = [];
		$rdata['isdate'] = $isdate;
		$rdata['datelist'] = $datelist;
		$rdata['status'] = 1;
		$rdata['address'] = $address;
		$rdata['linkman'] = $address ? $address['name'] : strval($userinfo['realname']);
		$rdata['tel'] = $address ? $address['tel'] : strval($userinfo['tel']);
		if(!$rdata['linkman']){
			$lastorder = Db::name('yuyue_order')->where('aid',aid)->where('mid',mid)->where('linkman','<>','')->find();
			if($lastorder){
				$rdata['linkman'] = $lastorder['linkman'];
				$rdata['tel'] = $lastorder['tel'];
			}
		}
		$rdata['userinfo'] = $userinfo;
		$rdata['allbuydata'] = $allbuydata;
		$rdata['fwtypelist'] = $fwtypelist;
		$rdata['yyset'] = $yyset;
		return $this->json($rdata);
	}

	public function createOrder(){
		$this->checklogin();
		$sysset = Db::name('admin_set')->where('aid',aid)->find();
		$post = input('post.');
		$buydata = $post['buydata'];

		$protype = -2;
		if($protype !=1){
			//收货地址
			if($post['fwtype']==1){
				$address = ['id'=>0,'name'=>$post['linkman'],'tel'=>$post['tel'],'area'=>'','address'=>''];
			}else{
				$address = Db::name('member_address')->where('id',$post['addressid'])->where('aid',aid)->where('mid',mid)->find();
				if(!$address['longitude'] || !$address['latitude']){
					$url = 'https://apis.map.qq.com/ws/geocoder/v1/?address='.$address['area'].$address['address'].'&key=ABLBZ-4BIKU-GFTVB-BK7IK-OLQ35-QCBFF';
					$res = json_decode(request_get($url),true);
					if($res && $res['status']==0){
						$data = [];
						$data['longitude'] = $res['result']['location']['lng'];
						$data['latitude'] = $res['result']['location']['lat'];
						Db::name('member_address')->where('id',$address['id'])->update($data);
					}
					$address = Db::name('member_address')->where('id',$address['id'])->find();
				}
				if(!$address) return $this->json(['status'=>0,'msg'=>'所选收货地址不存在']);
			}
		}

	    $userlevel = Db::name('member_level')->where('aid',aid)->where('id',$this->member['levelid'])->find();

		$couponridArr = [];
		foreach($buydata as $data){ //判断有没有重复选择的优惠券
			if($data['couponrid'] && in_array($data['couponrid'],$couponridArr)){
				return $this->json(['status'=>0,'msg'=>t('优惠券').'不可重复使用']);
			}elseif($data['couponrid']){
				$couponridArr[] = $data['couponrid'];
			}
		}
		$ordernum = date('ymdHis').rand(100000,999999);
		$i = 0;
		$alltotalprice = 0;

		foreach($buydata as $data){
			$i++;
			if($data['prodata']){
				$prodata = explode('-',$data['prodata']);
			}else{
				return $this->json(['status'=>0,'msg'=>'产品数据错误']);
			}
			$bid = $data['bid'];
			$product_priceArr = [];
			$product_price = 0;
			$balance_price = 0;
			$needzkproduct_price = 0;
			$givescore = 0;
			$totalnum = 0;
			$prolist = [];
			$proids = [];
			$cids = [];

			foreach($prodata as $key=>$pro){
				$sdata = explode(',',$pro);
				$sdata[2] = intval($sdata[2]);
				if($sdata[2] <= 0) return $this->json(['status'=>0,'msg'=>'购买数量有误']);
				$product = Db::name('yuyue_product')->where('aid',aid)->where('id',$sdata[0])->find();
				
				if($product['fwpeople']==1 && !$post['worker_id']){
					return $this->json(['status'=>0,'msg'=>'请选择服务人员']);
				}
				if(!$product) return $this->json(['status'=>0,'msg'=>'产品不存在或已下架']);
				if($product['status']==0){
					return $this->json(['status'=>0,'msg'=>'商品未上架']);
				}				
				if($product['status']==2 && (strtotime($product['start_time']) > time() || strtotime($product['end_time']) < time())){
					return $this->json(['status'=>0,'msg'=>'商品未上架']);
				}
				if($post['fwtype']==2 && $product['isareaxz']==1 && $product['areadata']){
					$isfuwu = false;
					$regionlist = explode('];',$product['areadata']);
					foreach($regionlist as $j=>$regiondata){
						$regiondata = explode('[',$regiondata);
						if(($regiondata[0] == $address['province'] && ($regiondata[1] == '全部地区' || in_array($address['city'],explode(',',$regiondata[1]))))){
							$isfuwu = true;
						}
					}
					if(!$isfuwu){
						return $this->json(['status'=>0,'msg'=>'该城市不在服务范围内，请重新选择']);
					}
				}

				if($key==0) $title = $product['name'];
				$guige = Db::name('yuyue_guige')->where('aid',aid)->where('id',$sdata[1])->find();
				if(!$guige) return $this->json(['status'=>0,'msg'=>'产品规格不存在或已下架']);

				$totalnum += $sdata[2];
				$product_price += $guige['sell_price'] * $sdata[2];
				$givescore += $guige['givescore'] * $sdata[2];
				if($product['balance']){
                    $balance_price += $product_price * $product['balance']*0.01;
                    $product_price = $product_price * (1-$product['balance']*0.01);
				}

				$product_priceArr[] = $guige['sell_price'] * $sdata[2];
				if($product['lvprice']==0 && $product['no_discount'] == 0){ //未开启会员价
					$needzkproduct_price += $guige['sell_price'] * $sdata[2];
				}
				$prolist[] = ['product'=>$product,'guige'=>$guige,'num'=>$sdata[2]];
				$proids[] = $product['id'];
				$cids = array_merge($cids,explode(',',$product['cid']));
			}
			$totalprice = $product_price;
		}
		//查看预约人数
		if(input('param.yydate')){
			$count = $this->getyytime(input('param.yydate'),$product['id']);
			if($count>=$product['yynum']){
                return $this->json(['status'=>0,'msg'=>'该段时间预约人数已满']);
			}
		}else{
			return $this->json(['status'=>0,'msg'=>'请选择预约时间']);
		}
		
		
		//查看该服务人员该时间是否已经预约出去
		if($post['worker_id']>0){
			$order = Db::name('yuyue_order')->where('aid',aid)->where('worker_id',$post['worker_id'])->where('status','in','1,2')->where('yy_time',$post['yydate'])->find();
			if($order){
				return $this->json(['status'=>0,'msg'=>'该段时间不可预约']);
			}
		}
	

		$yyset = db('yuyue_set')->where('aid',aid)->find();
		//会员折扣
		$leveldk_money = 0;
		if($yyset['discount']==1 && $userlevel && $userlevel['discount']>0 && $userlevel['discount']<10){
			$leveldk_money = $needzkproduct_price * (1 - $userlevel['discount'] * 0.1);
		}
		if($product_price>=$leveldk_money){
			$totalprice = $product_price - $leveldk_money;
		}else{
			$totalprice = 0;
		}
		//派单设置
		if($product['jiesuantype']==1){
			if( $balance_price>0){
				$product_price = $product_price+$balance_price;
			}
			$paidan_money = $product_price*$product['tc_bfb']/100;
		}else{
			if( $balance_price>0){
				$product_price = $product_price+$balance_price;
			}
			$paidan_money = $product['tcmoney'];
		}
		$yydate = explode('-',$post['yydate']);
		//开始时间
		$begindate = $yydate[0];
		if(strpos($begindate,'年') === false){
			$begindate = date('Y').'年'.$begindate;
		}
		$begindate = preg_replace(['/年|月/','/日/'],['-',''],$begindate);
		$date = date('Y-m-d H:i:s',strtotime(date('H:i',time())));
		$begintime = strtotime($begindate);
		if($begintime <= strtotime(date('H:i',time()))+$product['pdprehour']*60*60){
			return $this->json(['status'=>0,'msg'=>'预约时间已过，请选择其他时间']);
		}

		//优惠券
		if($data['couponrid'] > 0){
			$couponrid = $data['couponrid'];

			$bid = $data['bid'];
			if($bid > 0){
				$business = Db::name('business')->where('aid',aid)->where('id', $bid)->find();
				$bcids = $business['cid'] ? explode(',',$business['cid']) : [];
			}else{
				$bcids = [];
			}
			if($bcids){
				$whereCid = [];
				foreach($bcids as $bcid){
					$whereCid[] = "find_in_set({$bcid},canused_bcids)";
				}
				$whereCids = implode(' or ',$whereCid);
			}else{
				$whereCids = '0=1';
			}
			$couponrecord = Db::name('coupon_record')->where('aid',aid)->where('mid',mid)->where('id',$couponrid)
				->whereRaw("bid=-1 or bid=".$bid." or (bid=0 and (canused_bids='all' or find_in_set(".$bid.",canused_bids) or ($whereCids)))")->find();
			if(!$couponrecord){
				return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'不存在']);
			}elseif($couponrecord['status']!=0){
				return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'已使用过了']);
			}elseif($couponrecord['starttime'] > time()){
				return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'尚未开始使用']);	
			}elseif($couponrecord['endtime'] < time()){
				return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'已过期']);	
			}elseif($couponrecord['minprice'] > $totalprice){
				return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'不符合条件']);
			}elseif(!getcustom('yuyue_coupon') && $couponrecord['type']!=1 && $couponrecord['type']!=4 && $couponrecord['type']!=10){
				return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'不符合条件']);
			}
	
			$couponinfo = Db::name('coupon')->where('aid',aid)->where('id',$couponrecord['couponid'])->find();
            if(empty($couponinfo)){
                return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'不存在或已作废']);
            }
            if($couponrecord['from_mid']==0 && $couponinfo && $couponinfo['isgive']==2){
                return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'仅可转赠']);
            }
            //适用场景
            if($couponinfo['fwscene']!==0){
                return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'不符合条件']);
            }
            //0全场通用,4指定服务商品
            if(!in_array($couponinfo['fwtype'],[0,4])){
                return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'超出可用范围']);
            }
            if($couponinfo['fwtype']==4){//指定服务商品可用
                $productids = explode(',',$couponinfo['yuyue_productids']);
                if(!array_intersect($proids,$productids)){
                    return $this->json(['status'=>0,'msg'=>'该'.t('优惠券').'超出可用范围']);
                }
            }
			if($couponrecord['type']==1 || $couponrecord['type']==4){
				Db::name('coupon_record')->where('id',$couponrid)->update(['status'=>1,'usetime'=>time()]);
			}

			if($couponrecord['type']==4){//运费抵扣券
				$coupon_money = 0;
			}elseif($couponrecord['type']==3){//计次券 抵扣全部金额
				$coupon_money = $totalprice;
			}elseif($couponrecord['type']==10){//折扣券
				$coupon_money = $totalprice * (100 - $couponrecord['discount']) * 0.01;
			}else{
				$coupon_money = $couponrecord['money'];
				if($coupon_money > $totalprice) $coupon_money = $totalprice;
			}
		}else{
			$coupon_money = 0;
		}
		$totalprice = $totalprice - $coupon_money;
		$orderdata = [];

		//计次卡
		$orderdata['aid'] = aid;
		$orderdata['mid'] = mid;
		$orderdata['bid'] = $data['bid'];
		if(count($buydata) > 1){
			$orderdata['ordernum'] = $ordernum.'_'.$i;
		}else{
			$orderdata['ordernum'] = $ordernum;
		}

		$orderdata['title'] = $title.(count($prodata)>1?'等':'');
		$orderdata['linkman'] = $address['name'];
		$orderdata['tel'] = $address['tel'];
		$orderdata['area'] = $address['area'];
		$orderdata['address'] = $address['address'];
		$orderdata['longitude'] = $address['longitude'];
		$orderdata['latitude'] = $address['latitude'];
		$orderdata['area2'] = $address['province'].','.$address['city'].','.$address['district'];
		$orderdata['totalprice'] = $totalprice;
		if($totalprice == 0){
			$orderdata['status'] = 1;
			$orderdata['paytime'] = time();
		}
		$orderdata['leveldk_money'] = $leveldk_money;	//会员折扣
		$orderdata['product_price'] = $product_price;
		$orderdata['cost_price'] = $guige['cost_price'];
		$orderdata['givescore'] = $givescore;
		$orderdata['coupon_money'] = $coupon_money;		//优惠券抵扣
		$orderdata['coupon_rid'] = $couponrid;
		$orderdata['yy_time'] = $post['yydate']; //预约时间
		$orderdata['createtime'] = time();
		$orderdata['platform'] = platform;
		$orderdata['hexiao_code'] = random(16);
		$orderdata['remark'] = $post['remark'];
		$orderdata['proname'] = $product['name'];
		$orderdata['ggname'] = $guige['name'];
		$orderdata['num'] = $sdata[2];
		$orderdata['balance_price'] = $balance_price;	
		$orderdata['propic'] = $guige['pic'] ? $guige['pic'] : $product['pic'];
		$orderdata['proid'] = $product['id'];
		$orderdata['paidan_type'] = $product['fwpeople'];
		$orderdata['ggid'] = $guige['id'];
		$orderdata['worker_id'] = $post['worker_id'];
		$orderdata['fwtype'] = $post['fwtype']; //服务方式
		$orderdata['begintime'] = $begintime; 
		$orderdata['hexiao_qr'] = createqrcode(m_url('admin/hexiao/hexiao?type=yuyue&co='.$orderdata['hexiao_code']));
		$orderdata['paidan_money'] = $paidan_money;

	
		$orderid = Db::name('yuyue_order')->insertGetId($orderdata);

		$this->saveformdata($orderid,'yuyue_order',$data['formdata'],$product['id']);
		if($orderdata['status']==0 && $orderdata['totalprice']>0){
			$payorderid = \app\model\Payorder::createorder(aid,$orderdata['bid'],$orderdata['mid'],'yuyue',$orderid,$orderdata['ordernum'],$orderdata['title'],$orderdata['totalprice']);
		}else{
			if($yyset['paidantype']==0 && $yyset['isautopd']==1){
				$order = Db::name('yuyue_order')->where('id',$orderid)->find();
				$rs = \app\model\YuyueWorkerOrder::create($order,0,'');
			}
		}

        if($bid)
            $store_info = Db::name('business')->where('aid',aid)->where('id',$orderdata['bid'])->find();
        else
            $store_info = Db::name('admin_set')->where('aid',aid)->find();
        $store_name = $store_info['name'];

        //公众号通知 订单提交成功
        $tmplcontent = [];
        $tmplcontent['first'] = '有新预约订单提交成功';
        $tmplcontent['remark'] = '点击进入查看~';
        $tmplcontent['keyword1'] = $store_name; //店铺
        $tmplcontent['keyword2'] = date('Y-m-d H:i:s',$orderdata['createtime']);//下单时间
        $tmplcontent['keyword3'] = $orderdata['title'];//商品
        $tmplcontent['keyword4'] = $orderdata['totalprice'].'元';//金额
        $tempconNew = [];
        $tempconNew['character_string2'] = $orderdata['ordernum'];//订单号
        $tempconNew['thing8'] = $store_name;//门店名称
        $tempconNew['thing3'] = $orderdata['title'];//商品名称
        $tempconNew['amount7'] = $orderdata['totalprice'];//金额
        $tempconNew['time4'] = date('Y-m-d H:i:s',$orderdata['createtime']);//下单时间
        \app\common\Wechat::sendhttmpl(aid,$orderdata['bid'],'tmpl_orderconfirm',$tmplcontent,m_url('admin/order/yuyueorder'),$orderdata['mdid'],$tempconNew);

        $tmplcontent = [];
        $tmplcontent['thing11'] = $orderdata['title'];
        $tmplcontent['character_string2'] = $orderdata['ordernum'];
        $tmplcontent['phrase10'] = $orderdata['status']==0?'待付款':'已付款';
        $tmplcontent['amount13'] = $orderdata['totalprice'].'元';
        $tmplcontent['thing27'] = $this->member['nickname'];
        \app\common\Wechat::sendhtwxtmpl(aid,$orderdata['bid'],'tmpl_orderconfirm',$tmplcontent,'admin/order/yuyueorder',$orderdata['mdid']);

		if($orderdata['status']==1){
			//短信通知
			if($orderdata['tel']){
				$rs = \app\common\Sms::send(aid,$orderdata['tel'],'tmpl_yysucess',['name'=>$orderdata['title'],'time'=>$orderdata['yy_time']]);
			}
			if($orderdata['worker_id']){
				//如果用户已经支付成功且 选择服务人员直接进行派单
				$order = Db::name('yuyue_order')->where('id',$orderid)->find();
				$rs = \app\model\YuyueWorkerOrder::create($orderdata,$orderdata['worker_id'],'');
            }
		}
		if($balance_price > 0){
			$balancedata = [];
			$balancedata['aid'] = aid;
			$balancedata['bid'] = $orderdata['bid'];
			$balancedata['mid'] = $orderdata['mid'];
			$balancedata['orderid'] = $orderid;
			$balancedata['ordernum'] = $orderdata['ordernum'].'01';
			$balancedata['title'] = $orderdata['title'];
			$balancedata['money'] = $orderdata['balance_price'];
			$balancedata['type'] = 'yuyue_balance';
			$balancedata['score'] = 0;
			$balancedata['createtime'] = time();
			$balancedata['status'] = 0;
			$balance_pay_orderid = Db::name('payorder')->insertGetId($balancedata);
			Db::name('yuyue_order')->where('id',$orderid)->update(['balance_pay_orderid'=>$balance_pay_orderid]);
		}
		$num = $sdata[2];
		Db::name('yuyue_product')->where('aid',aid)->where('id',$product['id'])->update(['sales'=>Db::raw("sales+$num")]);

		return $this->json(['status'=>1,'payorderid'=>$payorderid,'msg'=>'提交成功']);
	}

	//保存自定义表单内容
	public function saveformdata($orderid,$type='yuyue_order',$formdata,$proid){
		if(!$orderid || !$formdata) return ['status'=>0];
		//根据orderid 取出proid
		$formfield = Db::name('yuyue_product')->where('id',$proid)->find();
		$formdataSet = json_decode($formfield['formdata'],true);
		//var_dump($formdataSet);die;
		$data = [];
		foreach($formdataSet as $k=>$v){
			$value = $formdata['form'.$k];
			if(is_array($value)){
				$value = implode(',',$value);
			}
			$value = strval($value);
			$data['form'.$k] = $v['val1'] . '^_^' .$value . '^_^' .$v['key'];
			if($v['val3']==1 && $value===''){
				return ['status'=>0,'msg'=>$v['val1'].' 必填'];
			}
		}
		$data['aid'] = aid;
		$data['type'] = 'yuyue_order';
		$data['orderid'] = $orderid;
		$data['createtime'] = time();
		Db::name('freight_formdata')->insert($data);
		return ['status'=>1];
	}
	//订单列表
	function orderlist(){
		$this->checklogin();
		$st = input('param.st');
		if(!$st && $st!=='0') $st = 'all';
		$pagenum = input('param.pagenum') ? input('param.pagenum') : 1;
		$where = [];
		$where[] = ['aid','=',aid];
		$where[] = ['mid','=',mid];
		$where[] = ['delete','=',0];
		if(input('param.keyword')) $where[] = ['ordernum|title', 'like', '%'.input('param.keyword').'%'];
		if($st == 'all'){
			
		}elseif($st == '0'){
			$where[] = ['status','=',0];
		}elseif($st == '1'){
			$where[] = ['status','=',1];
		}elseif($st == '2'){
			$where[] = ['status','=',2];
		}elseif($st == '3'){
			$where[] = ['status','=',3];
		}elseif($st == '4'){
			$where[] = ['status','=',4];
		}
		
		$datalist = Db::name('yuyue_order')->where($where)->order('id desc')->page($pagenum,10)->select()->toArray();
		if(!$datalist) $datalist = [];
		foreach($datalist as $key=>$v){
			if($v['bid']!=0){
				$datalist[$key]['binfo'] = Db::name('business')->where('aid',aid)->where('id',$v['bid'])->field('id,name,logo')->find();
			}
			//查看服务状态
			if($v['worker_orderid']>0){
				$datalist[$key]['worker'] = Db::name('yuyue_worker_order')->where('aid',aid)->where('id',$v['worker_orderid'])->field('id,status')->find();
			}
			$datalist[$key]['senddate'] = date('Y-m-d H:i:s',$v['send_time']);
		}
		$ishowpaidan=false;
		$rdata = [];
		$rdata['ishowpaidan'] = $ishowpaidan;
		$rdata['st'] = $st;
		$rdata['datalist'] = $datalist;
		return $this->json($rdata);
	}

	public function orderdetail(){
		$detail = Db::name('yuyue_order')->where('id',input('param.id/d'))->where('aid',aid)->where('mid',mid)->find();
		if(!$detail) return $this->json(['status'=>0,'msg'=>'订单不存在']);
		$detail['createtime'] = $detail['createtime'] ? date('Y-m-d H:i:s',$detail['createtime']) : '';
		$detail['collect_time'] = $detail['collect_time'] ? date('Y-m-d H:i:s',$detail['collect_time']) : '';
		$detail['paytime'] = $detail['paytime'] ? date('Y-m-d H:i:s',$detail['paytime']) : '';
		$detail['refund_time'] = $detail['refund_time'] ? date('Y-m-d H:i:s',$detail['refund_time']) : '';
		$detail['send_time'] = $detail['send_time'] ? date('Y-m-d H:i:s',$detail['send_time']) : '';
		$detail['formdata'] = \app\model\Freight::getformdata($detail['id'],'yuyue_order');
		$storeinfo = [];
		if($detail['freight_type'] == 1){
            $storeinfo = Db::name('mendian')->where('id',$detail['mdid'])->field('id,name,address,longitude,latitude')->find();
		}
		
		if($detail['bid'] > 0){
			$detail['binfo'] = Db::name('business')->where('aid',aid)->where('id',$detail['bid'])->field('id,name,logo,province,city,district,address')->find();
			$iscommentdp = 0;
			$commentdp = Db::name('business_comment')->where('orderid',$detail['id'])->where('aid',aid)->where('mid',mid)->find();
			if($commentdp) $iscommentdp = 1;
		}else{
			$detail['binfo'] = Db::name('admin_set')->where('aid',aid)->field('id,name,logo,province,city,district,address')->find();
			$iscommentdp = 1;
		}

		$prolist = Db::name('yuyue_order')->where('id',$detail['id'])->find();
		
		$yuyueset = Db::name('yuyue_set')->where('aid',aid)->field('autoclose')->find();
		
		if($detail['status']==0 && $yuyueset['autoclose'] > 0 && $detail['paytypeid'] != 5){
			$lefttime = strtotime($detail['createtime']) + $yuyueset['autoclose']*60 - time();
			if($lefttime < 0) $lefttime = 0;
		}else{
			$lefttime = 0;
		}
		
		$rdata = [];
		$rdata['status'] = 1;
		$rdata['detail'] = $detail;
		$rdata['iscommentdp'] = $iscommentdp;
		$rdata['prolist'] = $prolist;
		$rdata['storeinfo'] = $storeinfo;
		$rdata['lefttime'] = $lefttime;
		$rdata['codtxt'] = Db::name('shop_sysset')->where('aid',aid)->value('codtxt');

        //发票
        $rdata['invoice'] = 0;
        if($detail['bid']) {
            $rdata['invoice'] = Db::name('business')->where('aid',aid)->where('id',$detail['bid'])->value('invoice');
        } else {
            $rdata['invoice'] = Db::name('admin_set')->where('aid',aid)->value('invoice');
        }

		//定制 查看是否有工单可提交
		$rdata['isworkorder'] = 0;
		return $this->json($rdata);
	}
	function refund(){//申请退款
		$this->checklogin();
		if(request()->isPost()){
			$post = input('post.');
			$orderid = intval($post['orderid']);
			$money = floatval($post['money']);
			$order = Db::name('yuyue_order')->where('aid',aid)->where('mid',mid)->where('id',$orderid)->find();

			$workerorder = Db::name('yuyue_worker_order')->where('aid',aid)->where('id',$order['worker_orderid'])->find();
			if($order['worker_orderid']>0 && $workerorder['status']>0){
				return $this->json(['status'=>0,'msg'=>'订单接单后不允许退款']);
			}
			if(!$order || ($order['status']!=1 && $order['status'] != 2) || $order['refund_status'] == 2){
				return $this->json(['status'=>0,'msg'=>'订单状态不符合退款要求']);
			}
			if($money < 0 || $money > $order['totalprice']){
				return $this->json(['status'=>0,'msg'=>'退款金额有误']);
			}
			Db::name('yuyue_order')->where('aid',aid)->where('mid',mid)->where('id',$orderid)->update(['refund_time'=>time(),'refund_status'=>1,'refund_reason'=>$post['reason'],'refund_money'=>$money]);
            $tmplcontent = [];
            $tmplcontent['first'] = '有服务订单客户申请退款';
            $tmplcontent['remark'] = '点击进入查看~';
            $tmplcontent['keyword1'] = $order['ordernum'];
            $tmplcontent['keyword2'] = $money.'元';
            $tmplcontent['keyword3'] = $post['reason'];
            $tmplcontentNew = [];
            $tmplcontentNew['number2'] = $order['ordernum'];//订单号
            $tmplcontentNew['amount4'] = $money;//退款金额
            \app\common\Wechat::sendhttmpl(aid,$order['bid'],'tmpl_ordertui',$tmplcontent,m_url('admin/order/yuyueorder'),$order['mdid'],$tmplcontentNew);

            $tmplcontent = [];
            $tmplcontent['thing1'] = $order['title'];
            $tmplcontent['character_string4'] = $order['ordernum'];
            $tmplcontent['amount2'] = $order['totalprice'];
            $tmplcontent['amount9'] = $money.'元';
            $tmplcontent['thing10'] = $post['reason'];
            \app\common\Wechat::sendhtwxtmpl(aid,$order['bid'],'tmpl_ordertui',$tmplcontent,'admin/order/yuyueorder',$order['mdid']);

            return $this->json(['status'=>1,'msg'=>'提交成功,请等待商家审核']);
		}
		$rdata = [];
		$rdata['price'] = input('param.price/f');
		$rdata['orderid'] = input('param.orderid/d');
		$order = Db::name('yuyue_order')->where('aid',aid)->where('mid',mid)->where('id',$rdata['orderid'])->find();
		$rdata['price'] = $order['totalprice'];
		return $this->json($rdata);
	}

	 //获取接下来一周的日期
    function GetWeeks($yyzhouqi) {
		//查看今天周几
		$zqarr = explode(',',$yyzhouqi);
        $i=0;
        $weeks=[];
        for ($i;$i<7;$i++){
			$year=date('Y',time()+86400*$i).'年';
            $month=date('m',time()+86400*$i).'月';
            $day=date('d',time()+86400*$i);
            $week=date('w',time()+86400*$i);
            if ($week=='1'){
                $week='周一';
				$key=1;
            }elseif ($week=='2'){
                $week='周二';
				$key=2;
            }elseif ($week=='3'){
                $week='周三';
				$key=3;
            }elseif ($week=='4'){
                $week='周四';
				$key=4;
            }elseif ($week=='5'){
                $week='周五';
				$key =5;
            }elseif ($week=='6'){
                $week='周六';
				$key=6;
            }elseif ($week=='0'){
                $week='周日';
				$key=0;
            }
			$weeks[$i]['key'] = $key;
			$weeks[$i]['weeks'] = $week;
			$weeks[$i]['date'] = $month.$day;
			$weeks[$i]['year'] = $year;
            //array_push($weeks,$month.$day."(".$week."）");
			$newweek = [];
			foreach($weeks as $k=>$w){
				if(!in_array($w['key'],$zqarr)){
					unset($weeks[$k]);
				}
			}
        }
	    $weeks=array_values($weeks);
        return $weeks;
    }
	function logistics(){
		$get = input('param.');
		$worker_order = Db::name('yuyue_worker_order')->where('id',$get['express_no'])->find();
        $worker = Db::name('yuyue_worker')->where('id',$worker_order['worker_id'])->find();
        $orderinfo = json_decode($worker_order['orderinfo'],true);

		$order = Db::name('yuyue_order')->field('mid')->where('id',$orderinfo['id'])->find();
		$orderinfo['mid'] = $order['mid']; 
		$binfo = json_decode($worker_order['binfo'],true);
		$prolist = json_decode($worker_order['prolist'],true);
		
		if($worker_order['juli']> 1000){
			$worker_order['juli'] = round($worker_order['juli']/1000,1);
			$worker_order['juli_unit'] = 'km';
		}else{
			$worker_order['juli_unit'] = 'm';
		}
		//服务人员距用户的距离
		$juli2 = getdistance($worker_order['longitude2'],$worker_order['latitude2'],$worker['longitude'],$worker['latitude'],1);
		$worker_order['juli2'] = $juli2;
		if($juli2> 1000){
			$worker_order['juli2'] = round($juli2/1000,1);
			$worker_order['juli2_unit'] = 'km';
		}else{
			$worker_order['juli2_unit'] = 'm';
		}
		$worker_order['leftminute'] = ceil(($worker_order['yujitime'] - time()) / 60);
		$worker_order['ticheng'] = round($worker_order['ticheng'],2);
		if($worker_order['status']==3){
			$worker_order['useminute'] = ceil(($worker_order['endtime'] - $worker_order['createtime']) / 60);
			$worker_order['useminute2'] = ceil(($worker_order['endtime'] - $worker_order['starttime']) / 60); 
		}
	   $info = Db::name('yuyue_set')->where('aid',aid)->find();
		
		$yuyue_sign = false;
		$rdata = [];
		$rdata['worker_order'] = $worker_order;
		$rdata['mid'] = mid;
		$rdata['binfo'] = $binfo;
		$rdata['worker'] = $worker;
		$rdata['orderinfo'] = $orderinfo;
		$rdata['prolist'] = $prolist;
		$rdata['set'] = $info;
		$rdata['yuyue_sign'] =$yuyue_sign;
		return $this->json($rdata);
	}
	function closeOrder(){
		$post = input('post.');
		$orderid = intval($post['orderid']);
		$order = Db::name('yuyue_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->find();
		if(!$order || $order['status']>1){
			return $this->json(['status'=>0,'msg'=>'关闭失败,订单状态错误']);
		}
		//优惠券抵扣的返还
		if($order['coupon_rid'] > 0){
			//查看是不是计次卡
			$record = Db::name('coupon_record')->where('aid',aid)->where('mid',mid)->where('id',$order['coupon_rid'])->find();
			if(false){}else{
				Db::name('coupon_record')->where('aid',aid)->where('mid',mid)->where('id',$order['coupon_rid'])->update(['status'=>0,'usetime'=>'']);	
			} 
		}
		$rs = Db::name('yuyue_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->update(['status'=>4]);
		return $this->json(['status'=>1,'msg'=>'取消成功']);
	}
	function delOrder(){
		$post = input('post.');
		$orderid = intval($post['orderid']);
		$order = Db::name('yuyue_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->find();
		if(!$order || ($order['status']!=4 && $order['status']!=3)){
			return $this->json(['status'=>0,'msg'=>'删除失败,订单状态错误']);
		}
		if($order['status']==3){
			$rs = Db::name('yuyue_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->update(['delete'=>1]);
		}else{
			$rs = Db::name('yuyue_order')->where('id',$orderid)->where('aid',aid)->where('mid',mid)->delete();
		}
		return $this->json(['status'=>1,'msg'=>'删除成功']);
	}
	function orderCollect(){ //确认完成
		$post = input('post.');
		$orderid = intval($post['orderid']);
		$order = Db::name('yuyue_order')->where('aid',aid)->where('mid',mid)->where('id',$orderid)->find();
		if(!$order || ($order['status']!=2) || $order['paytypeid']==4){
			return $this->json(['status'=>0,'msg'=>'订单状态不符合收货要求']);
		}
		if($order['balance_price'] > 0 && $order['balance_pay_status']==0) return $this->json(['status'=>0,'msg'=>'请先支付尾款']);
		$rs = \app\common\Order::collect($order,'yuyue');
		if($rs['status'] == 0) return $this->json($rs);

		Db::name('yuyue_order')->where('aid',aid)->where('mid',mid)->where('id',$orderid)->update(['status'=>3,'collect_time'=>time()]);

		$return = ['status'=>1,'msg'=>'确认收货成功','url'=>true];
		

		$tmplcontent = [];
		$tmplcontent['first'] = '有订单客户已确认完成';
		$tmplcontent['remark'] = '点击进入查看~';
		$tmplcontent['keyword1'] = $this->member['nickname'];
		$tmplcontent['keyword2'] = $order['ordernum'];
		$tmplcontent['keyword3'] = $order['totalprice'].'元';
		$tmplcontent['keyword4'] = date('Y-m-d H:i',$order['paytime']);
        $tmplcontentNew = [];
        $tmplcontentNew['thing3'] = $this->member['nickname'];//收货人
        $tmplcontentNew['character_string7'] = $order['ordernum'];//订单号
        $tmplcontentNew['time8'] = date('Y-m-d H:i');//送达时间
		\app\common\Wechat::sendhttmpl(aid,$order['bid'],'tmpl_ordershouhuo',$tmplcontent,m_url('admin/order/yuyueorder'),$order['mdid'],$tmplcontentNew);

		
		$tmplcontent = [];
		$tmplcontent['thing2'] = $order['title'];
		$tmplcontent['character_string6'] = $order['ordernum'];
		$tmplcontent['thing3'] = $this->member['nickname'];
		$tmplcontent['date5'] = date('Y-m-d H:i');
		\app\common\Wechat::sendhtwxtmpl(aid,$order['bid'],'tmpl_ordershouhuo',$tmplcontent,'admin/order/yuyueorder',$order['mdid']);

		return $this->json($return);
	}
	//评价
	public function comment(){
		$oid = input('param.oid/d');
		$order = Db::name('yuyue_order')->where('id',$oid)->where('mid',mid)->find();
		if(!$order){
			return $this->json(['status'=>0,'msg'=>'未查找到相关记录']);
		}
		$comment = Db::name('yuyue_comment')->where('orderid',$oid)->where('aid',aid)->where('mid',mid)->find();
		if(request()->isPost()){
			if($comment){
				return $this->json(['status'=>0,'msg'=>'您已经评价过了']);
			}		
			$content = input('post.content');
			$content_pic = input('post.content_pic');
			$score = input('post.score/d');
			if($score < 1){
				return $this->json(['status'=>0,'msg'=>'请打分']);
			}
            $yuyueset = Db::name('yuyue_set')->where('aid',aid)->where('bid',0)->find();
			$data['aid'] = aid;
			$data['mid'] = mid;
			$data['bid'] = $order['bid'];
			$data['proid'] =$order['proid'];
			$data['proname'] = $order['proname'];
			$data['propic'] = $order['propic'];
			$data['orderid']= $order['id'];
			$data['ordernum']= $order['ordernum'];
			$data['score'] = $score;
			$data['content'] = $content;
			$data['openid']= $this->member['openid'];
			$data['nickname']= $this->member['nickname'];
			$data['headimg'] = $this->member['headimg'];
			$data['createtime'] = time();
			$data['content_pic'] = $content_pic;
			$data['ggid'] = $order['ggid'];
			$data['ggname'] = $order['ggname'];
			$data['status'] = ($yuyueset['comment_check']==1 ? 0 : 1);
			Db::name('yuyue_comment')->insert($data);
			Db::name('yuyue_order')->where('aid',aid)->where('mid',mid)->where('id',$oid)->update(['iscomment'=>1]);

			//如果不需要审核 增加产品评论数及评分
			if($yuyueset['comment_check']==0){
				$countnum = Db::name('yuyue_comment')->where('proid',$order['proid'])->where('status',1)->count();
				$score = Db::name('yuyue_comment')->where('proid',$order['proid'])->where('status',1)->avg('score'); //平均评分
				$haonum = Db::name('yuyue_comment')->where('proid',$order['proid'])->where('status',1)->where('score','>',3)->count(); //好评数
				if($countnum > 0){
					$haopercent = $haonum/$countnum*100;
				}else{
					$haopercent = 100;
				}
				Db::name('yuyue_product')->where('id',$order['proid'])->update(['comment_num'=>$countnum,'comment_score'=>$score,'comment_haopercent'=>$haopercent]);
			}
			return $this->json(['status'=>1,'msg'=>'评价成功']);
		}
		$rdata = [];
		$rdata['order'] = $order;
		$rdata['comment'] = $comment;
		return $this->json($rdata);
	}
	//评价服务人员
	public function commentps(){
		$id = input('param.id/d');
		$worker_order = Db::name('yuyue_worker_order')->where('id',$id)->where('mid',mid)->find();
		if(!$worker_order) return $this->json(['status'=>0,'msg'=>'未找到相关记录']);
		$comment = Db::name('yuyue_worker_comment')->where('orderid',$id)->where('aid',aid)->where('mid',mid)->find();
		if(request()->isPost()){
			if($comment){
				return $this->json(['status'=>0,'msg'=>'您已经评价过了']);
			}
			$content = input('post.content');
			$content_pic = input('post.content_pic');
			$score = input('post.score/d');
			if($score < 1){
				return $this->json(['status'=>0,'msg'=>'请打分']);
			}
			$data['aid'] = aid;
			$data['mid'] = mid;
			$data['bid'] = $worker_order['bid'];
			$data['worker_id'] = $worker_order['worker_id'];
			$data['orderid']= $worker_order['id'];
			$data['ordernum']= $worker_order['ordernum'];
			$data['score'] = $score;
			$data['content'] = $content;
			$data['content_pic'] = $content_pic;
			$data['nickname']= $this->member['nickname'];
			$data['headimg'] = $this->member['headimg'];
			$data['createtime'] = time();
			$data['status'] = 1;
			Db::name('yuyue_worker_comment')->insert($data);
			
			//如果不需要审核 增加配送员评论数及评分
			$countnum = Db::name('yuyue_worker_comment')->where('worker_id',$worker_order['worker_id'])->where('status',1)->count();
			$avgscore = Db::name('yuyue_worker_comment')->where('worker_id',$worker_order['worker_id'])->where('status',1)->avg('score'); //平均评分
			$haonum = Db::name('yuyue_worker_comment')->where('worker_id',$worker_order['worker_id'])->where('status',1)->where('score','>',3)->count(); //好评数
			if($countnum > 0){
				$haopercent = $haonum/$countnum*100;
			}else{
				$haopercent = 100;
			}
			Db::name('yuyue_worker')->where('id',$worker_order['worker_id'])->update(['comment_haopercent'=>$haopercent,'comment_score'=>$avgscore]);
			Db::name('yuyue_worker_order')->where('id',$worker_order['worker_id'])->update(['comment_num'=>$countnum,'comment_score'=>$score,'comment_haopercent'=>$haopercent]);

			return $this->json(['status'=>1,'msg'=>'评价成功']);
		}
		$rdata = [];
		$rdata['worker_order'] = $worker_order;
		$rdata['comment'] = $comment;
		return $this->json($rdata);
	}

	public function selectpeople(){
		$bid = input('param.bid');
		if(!$bid) $bid = 0;
		$type = input('param.type');
		$pernum = 10;
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
		if($type=='list'){
			$where = [];
			$where[] = ['aid','=',aid];
			$where[] = ['bid','=',$bid];
			$where[] = Db::raw("`status`=1");

			$longitude = input('post.longitude');
			$latitude = input('post.latitude');
			if(false){}else{
				$orderBy = 'sort desc,id';
			}
			if(input('param.cid')){
						$where[] = ['cid','=',input('param.cid')];	
			}
			if(input('param.keyword')){
				$where[] = ['realname','like','%'.input('param.keyword').'%'];
			}
			$datalist = Db::name('yuyue_worker')->where($where)->page($pagenum,$pernum)->order($orderBy)->select()->toArray();
			foreach($datalist as &$d){
				$type =   Db::name('yuyue_worker_category')->where(['id'=>$d['cid']])->find();
				$d['typename'] = $type['name'];
			}
		}else{
			$pro =explode(',',input('param.prodata'));
			$yydate = input('param.yydate');
			$product = Db::name('yuyue_product')->field('fwpeoid')->where('id',$pro[0])->find();
			$peoarr = explode(',',$product['fwpeoid']);
			$datalist = Db::name('yuyue_worker')->where('aid',aid)->where('status',1)->where('id','in',$peoarr)->order('sort desc,id')->select()->toArray();
			//查看该时间是否已经预约出去
			foreach($datalist as &$d){
				$type = Db::name('yuyue_worker_category')->where(['id'=>$d['cid']])->find();
				$d['typename'] = $type['name'];
				$order = Db::name('yuyue_order')->where('aid',aid)->where('worker_id',$d['id'])->where('status','in','1,2')->where('yy_time',$yydate)->find();
				$d['yystatus']=1;
				if($order){
					$d['yystatus']=-1;
				}
			}
		}
		
		if(!$datalist) $datalist = [];
		return $this->json(['status'=>1,'data'=>$datalist]);
	}

	//人员分类
	public function peocategory(){
		$bid = input('param.bid');
		if(!$bid) $bid = 0;
		$clist = Db::name('yuyue_worker_category')->where('aid',aid)->where('bid',$bid)->where('pid',0)->where('status',1)->order('sort desc,id')->select()->toArray();
		return $this->json(['status'=>1,'data'=>$clist]);
	}

	//人员详情
	public function peodetail(){
		$id = input('param.id/d');
		$detail = Db::name('yuyue_worker')->where('id',$id)->where('aid',aid)->find();
		$type = Db::name('yuyue_worker_category')->where(['id'=>$detail['cid']])->find();
		$detail['typename'] = $type['name'];
		//服务商品数量
		$detail['count'] = 0+Db::name('yuyue_product')->where('aid',aid)->where("find_in_set({$id},fwpeoid)")->count();
		$detail['showdesc'] = false;
		//获取设置
        $set = Db::name('yuyue_set')->field('ad_status,ad_pic,ad_link,video_status,video_tag,video_title')->where('aid',aid)->where('bid',0)->find();
        if($set['video_tag']) $set['video_tag'] = explode(',',$set['video_tag']);
        else $set['video_tag'] = [];
		if(!$detail) return $this->json(['status'=>0,'msg'=>'不存在']);
		return $this->json(['status'=>1,'data'=>$detail,'set'=>$set]);
	}
	public function getdlist(){
		$id = input('param.id/d');
		$type =	input('param.curTopIndex/d');
		$pernum = 10;
		$pagenum = input('post.pagenum');
		if(!$pagenum) $pagenum = 1;
        $order = 'id desc';
		if($type==0){
			//服务商品
			$datalist = Db::name('yuyue_product')->where('aid',aid)->where("find_in_set({$id},fwpeoid)")->page($pagenum,$pernum)->order($order)->select()->toArray();
		}
		if($type==1){
			//	//评价列表
			$datalist = Db::name('yuyue_worker_comment')->where(['aid'=>aid,'worker_id'=>$id])->page($pagenum,$pernum)->order($order)->select()->toArray();
			foreach($datalist as $k=>$pl){
				$datalist[$k]['createtime'] = date('Y-m-d H:i',$pl['createtime']);
				if($datalist[$k]['content_pic']) $datalist[$k]['content_pic'] = explode(',',$datalist[$k]['content_pic']);
			}
		}
		if(!$datalist) $datalist = [];
		$datalist = $this->formatprolist($datalist);
		return $this->json(['status'=>1,'data'=>$datalist]);
	}

	public function isgettime(){
		$date = input('param.date/t');
		if(strpos($date,'年') === false){
			$date = date('Y').'年'.$date;
		}
		$proid = input('param.proid/d');
		//获取设置
	    $product = Db::name('yuyue_product')->where('aid',aid)->where('id',$proid)->find();
		$sets = Db::name('yuyue_set')->where('aid',aid)->find();
		if($product['datetype']==1){
			$timearr = [];
			$j=0;
			$nowdate =strtotime(date('H:i',time()))+$product['pdprehour']*60*60;
			for($i=strtotime($product['zaohour'].':00') ;$i<=strtotime($product['wanhour'].':00') ; $i=$i+60*$product['timejg']){
				$j++;
				$time =strtotime(preg_replace(['/年|月/','/日/'],['-',''],$date.' '.date("H:i",$i)));
				$count = Db::name('yuyue_order')->where('aid',aid)->where('proid',$proid)->where('begintime','=',$time)->where('status','in','1,2')->count();
				$order=Db::name('yuyue_order')->where('aid',aid)->where('proid',$proid)->where('begintime','=',$time)->where('status','in','1,2')->find();
			
					if($count>=$product['yynum'] || $time<$nowdate){
						$timearr[$j]['status'] = 0;
					}else{
						$timearr[$j]['status'] = 1;
					}
					$timearr[$j]['time'] = date("H:i",$i);
					$timearr[$j]['timeint'] = str_replace(':','',date("H:i",$i));
			 }
		}
		if($product['datetype']==2){
			$timearr = [];
			$timearrs = explode(',',$product['timepoint']); 
			$nowdate =strtotime(date('H:i',time()))+$product['pdprehour']*60*60;	
			foreach($timearrs as $k=>$t){
				$time =strtotime(preg_replace(['/年|月/','/日/'],['-',''],$date.' '.$t));
				$count = Db::name('yuyue_order')->where('aid',aid)->where('proid',$proid)->where('begintime','=',$time)->where('status','in','1,2')->count();
				if($count>=$product['yynum'] || $time<$nowdate){
						$timearr[$k]['status'] = 0;
				}else{
						$timearr[$k]['status'] = 1;
				}
				$timearr[$k]['time'] = $t;
				$timearr[$k]['timeint'] = str_replace(':','',$t);
			}
		}
		return $this->json(['status'=>1,'data'=>$timearr]);
	}
	public function getyytime($yydate,$proid){
		$yydate = explode('-',$yydate);
		//开始时间
		$begindate = date('Y年').$yydate[0];
		$begindate = preg_replace(['/年|月/','/日/'],['-',''],$begindate);
		$begintime = strtotime($begindate);
		$ends = explode(' ',$yydate[0]);

		$where[] = ['begintime','=',$begintime];
		$count = 0 + Db::name('yuyue_order')->where($where)->where('aid',aid)->where('status','in','1,2')->where('proid',$proid)->count();
		return $count;
	}

	//申请  0616
	public function apply(){
		$set = Db::name('yuyue_set')->field('apply_paymoney,xieyi_show,xieyi,apply_url')->where('aid',aid)->find();
		if(input('param.bid')){
			$bid = input('param.bid/d');
		}else{
			$bid = 0;
		}
		if(request()->isPost()){
			$formdata = input('post.info/a');
			//查看是否已经存在此账号
			$worker = Db::name('yuyue_worker')->where('aid',aid)->where('bid',$bid)->where('un',$formdata['un'])->find();
			if($worker['mid'] && $worker['mid']!=mid){
				return $this->json(['status'=>0,'msg'=>'此登录账号已存在']);	
			}
			if(!$formdata['realname'] || !$formdata['tel'] || !$formdata['un']){
				return $this->json(['status'=>0,'msg'=>'请将信息填写完整']);	
			}
			$info = [];
			$info['aid'] = aid;
			$info['mid'] = mid;
			$info['bid'] = $formdata['bid']?$formdata['bid']:0;
			$info['cid'] = $formdata['cid'];
			$info['realname'] = $formdata['realname'];
			$info['tel'] = $formdata['tel'];
			$info['age'] = $formdata['age'];
			$info['sex'] = $formdata['sex'];
			$info['tel'] = $formdata['tel'];
			$info['citys'] = $formdata['citys'];
			$info['latitude'] = $formdata['latitude'];
			$info['longitude'] = $formdata['longitude'];
			$info['fuwu_juli'] = $formdata['fuwu_juli'];
			$info['codepic'] = $formdata['codepic'];
			$info['otherpic'] = $formdata['otherpic'];
			$info['headimg'] = $formdata['headimg'];
			$info['un'] = $formdata['un'];
			$info['desc'] = $formdata['desc'];
			$info['apply_paymoney'] = $set['apply_paymoney']?$set['apply_paymoney']:0;
			if($formdata['pwd']!='') $info['pwd'] = md5($info['pwd']);
			$info['status'] = 0;
			$info['shstatus'] = 0;
			$info['createtime'] = time();
			$ordernum = \app\common\Common::generateOrderNo(aid);
			$info['ordernum'] = $ordernum;
			$info['fwcids'] = implode(',',$formdata['fwcids']);
			if($formdata['id']){
				Db::name('yuyue_worker')->where('aid',aid)->where('bid',$info['bid'])->where('id',$formdata['id'])->update($info);
			}else{
				$worker_id = Db::name('yuyue_worker')->insertGetId($info);
			}

			if($set['apply_paymoney']>0){  //创建支付订单
				$orderdata = [];
				$orderdata['aid'] = aid;
				$orderdata['mid'] = mid;
				$orderdata['bid'] = $bid;
				$orderdata['worker_id'] = $worker_id;
				$orderdata['ordernum'] = $ordernum;
				$orderdata['createtime'] = time();
				$orderdata['status'] = 0;
				$orderdata['price'] = $info['apply_paymoney'];
				$orderdata['title'] = $formdata['realname'].'师傅申请';
				$order_id = Db::name('yuyue_workerapply_order')->insertGetId($orderdata);
				$payorderid = \app\model\Payorder::createorder(aid,$info['bid'],mid,'yuyue_workerapply',$order_id,$ordernum,'预约师傅申请',$info['apply_paymoney'],0);
		
				return $this->json(['status'=>1,'payorderid'=>$payorderid,'msg'=>'提交成功']);
			}else{
				
				//入驻成功给管理员发通知
				$tmplcontent = [];
				$tmplcontent['first'] = '有师傅申请成功';
				$tmplcontent['remark'] = '请登录后台，查看申请详情~';
				$tmplcontent['keyword1'] = '预约师傅申请';
				$tmplcontent['keyword2'] = date('Y-m-d H:i');
                $tempconNew = [];
                $tempconNew['thing3'] = '预约师傅申请';//报名名称
                $tempconNew['time5'] = date('Y-m-d H:i');//申请时间
				\app\common\Wechat::sendhttmpl(aid,$formdata['bid'],'tmpl_formsub',$tmplcontent,'',0,$tempconNew);
				return $this->json(['status'=>1,'msg'=>'提交成功,请等待审核','tourl'=>$set['apply_url']?$set['apply_url']:'apply']);
			}
		}
		if(mid>0){
			$info = Db::name('yuyue_worker')->where('aid',aid)->where('mid',mid)->find();
			if($info && $info['shstatus']==1){
				//var_dump($info);
				return $this->json(['status'=>2,'msg'=>'您已成功入驻']); 
			}
		}else{
			return $this->json(['status'=>-1,'msg'=>'请先登录']); 
		}

		$clist = Db::name('yuyue_worker_category')->where('aid',aid)->where('status',1)->where('bid',$bid)->order('sort desc,id')->select()->toArray();
		//商家
		$blist1 = [['id'=>'0','name'=>'平台自营']];
		$blist = Db::name('business')->where('aid',aid)->where('status',1)->order('sort desc,id')->select()->toArray();
		$blist = array_merge($blist1,$blist);
		//查看订单表
	 	$order = Db::name('yuyue_workerapply_order')->where(['aid'=>aid,'bid'=>$bid,'mid'=>mid])->order('id desc')->find();

		$fwcateArr = Db::name('yuyue_category')->Field('id,name')->where('aid',aid)->column('name','id');
		$busarr = Db::name('business')->Field('id,name')->where('aid',aid)->column('name','id');

		$isapply2=false;
		$rdata = []; 
        $rdata['title'] = '申请入驻';
		$rdata['clist'] = $clist;
		$rdata['set'] = $set;
		$rdata['blist'] = $blist;
		$rdata['fwcateArr'] = $fwcateArr;
		$rdata['order'] = $order?$order:[];
		if(!$info) $info=array('id'=>'');
		$rdata['info'] = $info;
		$rdata['fwcids'] = $info['fwcids'] ? explode(',',$info['fwcids']) : [];
		$rdata['busarr'] = $busarr ? $busarr : [];
		$rdata['isapply2'] = $isapply2;
		return $this->json($rdata);
	}

}